package com.frinder.official.akka.actors;

import akka.actor.AbstractActor;
import akka.actor.ActorIdentity;
import akka.actor.ActorRef;
import akka.actor.Identify;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import scala.Option;

import java.util.Optional;

/**
 * Created by frinder on 2017/9/12.
 * <p>
 * 注：基于 Spring的 Actor 必须配置为 @Scope("prototype")
 */
@Component
@Scope("prototype")
public class MyActor extends AbstractActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);


    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(String.class, s -> {
                    log.debug("Received String message: {}", s);
                    getSender().tell(s, getSelf());
                })
                .match(Identify.class, identify -> {
                    log.debug("Received identify message: {}", identify);
                    ActorIdentity actorIdentity = new ActorIdentity(identify, Option.apply(getSelf()));
                    getSender().tell(actorIdentity, getSelf());
                })
                .matchAny(o -> log.info("received unknown message"))
                .build();
    }

}
